<?php

namespace Xtsb\Cims\Btn;
use Xtsb\Cims\Excel\ExcelFactory;
use Xtsb\Cims\Exception\ApiException;
use Xtsb\Cims\Error\ApiErrorDesc;
use think\facade\Db;

class StatusHelper
{
  static function isInsertFail($res,$error='新增失败'){
    if(!$res){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT,$error);
    }
  }

  static function isDeleteFail($res){
    if(!$res){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT,'删除失败');
    }
    return $res;
  }

  static function isUpdateFail($res,$error='更新失败'){
    if(!$res){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT,$error);
    }
  }

  static function isImportFail($respon){
    if (empty($respon) || count($respon) == 0) {
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, '导入数据不能为空');
    }
  }

  static function isExistFail($count,$error){
    if($count > 0){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $error);
    }
  }

  static function isDataNotFount($data,$error='无数据'){
    if(!$data || count($data) == 0){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT,$error);
    }
    return $data;
  }


  static function falseFail($res,$error){
    if(!$res){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $error);
    }
    return $res;
  }

  static function trueFail($res,$error){
    if($res){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $error);
    }
    return $res;
  }



  static function fail($result){
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode(['code' => 500, 'message' => '操作失败', 'data' => $result], JSON_UNESCAPED_UNICODE));
  }

  /**财务费用检测
   * @param $where
   */
  static function isCostExist($where){
    if(Db::name("cost_apply")->where($where)->count() > 0){
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT,'已经进行了票据登记，请先删除相关财务数据');
    }
  }

  /**获取流程
   * @param $code
   * @param string $error
   * @return mixed
   */
  static function isApmExist($code,$error='请先设置对应的流程后再进行操作'){
    $apm_id = Db::name('apm')->where(['cuid' => CUID, 'code' => $code])->value('id');
    if (!$apm_id) {
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $error);
    }
    return $apm_id;
  }

  static function veiwTableColumns($table_name,$is_in_list=null){
    $columns = Db::query(" SELECT
                            COLUMN_NAME NAME,
                            COLUMN_COMMENT COMMENT
                          FROM
                            INFORMATION_SCHEMA. COLUMNS
                          WHERE
                            table_name = 'xtsb_{$table_name}'
                          AND table_schema = 'xtsb_cims'");
    $list = array_column($columns,'NAME');
    if($is_in_list){
      $in = [];
      foreach ($is_in_list as $each){
        if(in_array($each,$list)){
          array_push($in,$each);
        }
      }
      self::fail($in);
    }
    self::fail($list);
  }

  static function checkDateFormation($index,$err_msg,&$data){
    $date = $data[$index]??"";
    if ($date) {
      if(strtotime($date) === false && !(int)$date){
        throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $err_msg);
      }

      $new_date = excel_time($date);
      if($new_date =='error'){
        throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, $err_msg);
      }
      $data[$index] = $new_date;
    }else{
      unset($data[$index]);
    }
  }

  static function isCeo(){
    if (!is_ceo()) {
      throw new ApiException(ApiErrorDesc::ERROR_DEFAULT, '权限不足');
    }
  }

  static function arrayItemStringToInt(&$array){
    foreach ($array as &$each) {
      $each = (int)$each;
    }
  }

  static function arrayItemStringToIntKV(&$array,$index){
    foreach ($array as &$each) {
      $each[$index] = (int)$each[$index];
    }
  }

  /**索引页页眉转换excel页眉
   * @param $table
   */
  static function tableHeadToExcelHead($table){
    $text = "";
    foreach ($table as $each){
      if($each['name'] != 'operation'){
        $text.= "'{$each['name']}',";
      }
    }
    echo $text;die;
  }

  /**索引页元素转换excel元素
   * @param $list
   */
  static function tableColumnToExcelColumn($table){
   $text = "";
    foreach ($table as $each){
      if($each['name'] != 'operation'){
        $text.= "['value'=>'{$each['label']}', 'style' => ['colNum' => 1, 'rowNum' => 1, 'colWidth' => 20]],<br/>";
      }
    }
    echo $text;die;
  }

  static function getExcelResult($list,$keyArray,$datas,$fileName,$i=2){
    foreach ($list as $key => $value) {
      foreach ($keyArray as $k => $val) {
        if ($val == 'sn') {
          $datas[$i][$k]['value'] = $key + 1;
          $datas[$i][$k]['format'] = 'int';
        } else {
          $datas[$i][$k]['value'] = $value[$val] ?? '';
        }
      }
      $i++;
    }
    $result['data'] = $datas;
    $result['filename'] = $fileName . '_' . date('YmdHis') . '.xlsx';
    return $result;
  }

  static function getMinuteBetweenTime($end,$start){
    $time = (strtotime($end) - strtotime($start));

    return $time == 0 ?0:($time/60) ;
  }

  static function assignValueByBoolean($boolean,&$old,$new){
    if($boolean){
      $old = $new;
    }
  }

  static function addValueByBoolean($boolean,&$attr,$value){
    if($boolean){
      $attr+=$value;
    }
  }

  static function attrIncrementByBoolean($boolean,&$attr){
    if($boolean){
      $attr++;
    }
  }

  public static function getPayStatus($payed, $amount)
  {
    if (!$payed || $payed == 0) {
      return '<span style="color:red">未付款</span>';
    } elseif ($payed < $amount) {
      return '<span style="color:orange">部分付款</span>';
    } elseif ($payed == $amount) {
      return '<span style="color:green">已付款</span>';
    }
    return '<span style="color:green">已付款</span>';
  }

}